<template>
  <div class="container">
    <!-- 表格展示组织结构 -->
    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%; margin-top: 20px"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: false }"
      default-expand-all
    >
      <el-table-column prop="levelLabel" label="组织层级" width="200" />
      <el-table-column prop="organizationName" label="组织机构名称" />
      <el-table-column prop="province" label="省域" />
      <el-table-column prop="description" label="备注" />
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button
            v-if="scope.row.level === 1 && hasPermission(authStore.permissions, 31) || scope.row.level === 0 && hasPermission(authStore.permissions, 31)"
            link
            style=" color: rgb(110, 78, 208)"
            size="small"
            @click="append(scope.row)"
          >添加</el-button>

          <template v-if="scope.row.level !== 0">
            <el-button
              v-if="hasPermission(authStore.permissions, 32)"
              link
              style="color: rgb(110, 78, 208)"
              size="small"
              @click="change(scope.row)"
            >修改</el-button>
            <el-button
              v-if="hasPermission(authStore.permissions, 33)"
              link
              style=" color:red"
              size="small"
              @click="remove(scope.row)"
            >删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加弹窗 -->
    <el-dialog v-model="visible" :show-close="false" width="500">
  <template #header="{ close }">
    <div class="my-header">
      <div>添加</div>
      <el-button type="danger" @click="close">
        <el-icon><CircleCloseFilled /></el-icon>
      </el-button>
    </div>
  </template>
  <div>
    <div class="input-text"><span class="required">*</span>上级机构：</div>
    <el-input v-model="upOrganization" disabled />

    <div class="input-text"><span class="required">*</span>组织机构名称：</div>
    <el-input v-model="newOrganizationName" @input="orgFormErrors.name = false" />
    <p v-if="orgFormErrors.name" class="error-text">组织机构名称不能为空</p>

    <template v-if="upOrganization !== '中国铁塔股份有限公司安徽省分公司'">
      <div class="input-text"><span class="required"></span>所在省域：</div>
      <el-select
        v-model="OrganizationLocation"
        placeholder="所在省域"
        filterable
        clearable
        @change="orgFormErrors.location = false"
      >
       <el-option
          v-for="item in provinces"
          :key="item.value1"
          :label="item.label1"
          :value="item.value1"
        />
      </el-select>

      <div class="input-text"><span class="required"></span>备注：</div>
      <el-input v-model="message" @input="orgFormErrors.message = false" />
    </template>
  </div>
  <div style="margin-top: 2rem; text-align: right">
    <el-button @click="visible = false">取消</el-button>
    <el-button type="primary" @click="validateAddForm() && sumbitMessage()">保存</el-button>
  </div>
</el-dialog>


    <!-- 修改弹窗 -->
    <el-dialog v-model="visible1" :show-close="false" width="500">
  <template #header="{ close }">
    <div class="my-header">
      <div>修改</div>
      <el-button type="danger" @click="close">
        <el-icon><CircleCloseFilled /></el-icon>
      </el-button>
    </div>
  </template>
  <div>

    <div class="input-text"><span class="required"></span>上级机构名称：</div>
    <el-input v-model="secondaryName"  disabled="true" />

    <div class="input-text"><span class="required">*</span>组织机构名称：</div>
    <el-input v-model="newOrganizationName" @input="orgFormErrors.name = false" />
    <p v-if="orgFormErrors.name" class="error-text">组织机构名称不能为空</p>

    <template v-if="changeOrangLevel == '2'">
      <div class="input-text"><span class="required"></span>所在省域：</div>
      <el-select v-model="OrganizationLocation" placeholder="所在省域" @change="orgFormErrors.location = false">
        <el-option v-for="item in provinces" :key="item.value1" :label="item.label1" :value="item.value1" />
      </el-select>
      <p v-if="orgFormErrors.location" class="error-text">请选择所在省域</p>

      <div class="input-text"><span class="required"></span>备注：</div>
      <el-input v-model="message" @input="orgFormErrors.message = false" />
      <p v-if="orgFormErrors.message" class="error-text">备注不能为空</p>
    </template>
  </div>
  <div style="margin-top: 2rem; text-align: right">
    <el-button @click="visible1 = false">取消</el-button>
    <el-button type="primary" @click="validateEditForm() && changeMessage()">修改</el-button>
  </div>
</el-dialog>


    <!-- 删除确认提示框 -->
    <el-dialog v-model="centerDialogVisible" title="提示" width="500" center>
      <span>是否需要删除组织 "{{ deleteItem.organizationName }}"</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="deleteOri()">确认删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { CircleCloseFilled, Delete, Edit, DocumentAdd } from '@element-plus/icons-vue';
import request from '@/utils/request';
import { useAuthStore } from '@/stores/user';
import { hasPermission } from '@/utils/permissionUtils';
import showMessage from '@/utils/showMessage';


const authStore = useAuthStore();
const visible = ref(false);
const visible1 = ref(false);
const centerDialogVisible = ref(false);
const changeId = ref<any>();
const changeItem = ref();
const deleteItem = ref();
const upOrganization = ref('');
const upOrganizationId = ref<number>();
const newOrganizationName = ref('');
const secondaryName = ref('');
const OrganizationLocation = ref('');
const message = ref('');
const NewsecondId = ref<number>();
const orgFormErrors = ref({
  name: false,
  location: false,
  message: false
});
const provinces = [
{ value1: '北京市', label1: '北京市' },
  { value1: '天津市', label1: '天津市' },
  { value1: '上海市', label1: '上海市' },
  { value1: '重庆市', label1: '重庆市' },
  { value1: '河北省', label1: '河北省' },
  { value1: '山西省', label1: '山西省' },
  { value1: '辽宁省', label1: '辽宁省' },
  { value1: '吉林省', label1: '吉林省' },
  { value1: '黑龙江省', label1: '黑龙江省' },
  { value1: '江苏省', label1: '江苏省' },
  { value1: '浙江省', label1: '浙江省' },
  { value1: '安徽省', label1: '安徽省' },
  { value1: '福建省', label1: '福建省' },
  { value1: '江西省', label1: '江西省' },
  { value1: '山东省', label1: '山东省' },
  { value1: '河南省', label1: '河南省' },
  { value1: '湖北省', label1: '湖北省' },
  { value1: '湖南省', label1: '湖南省' },
  { value1: '广东省', label1: '广东省' },
  { value1: '海南省', label1: '海南省' },
  { value1: '四川省', label1: '四川省' },
  { value1: '贵州省', label1: '贵州省' },
  { value1: '云南省', label1: '云南省' },
  { value1: '陕西省', label1: '陕西省' },
  { value1: '甘肃省', label1: '甘肃省' },
  { value1: '青海省', label1: '青海省' },
  { value1: '台湾省', label1: '台湾省' },
  { value1: '内蒙古自治区', label1: '内蒙古自治区' },
  { value1: '广西壮族自治区', label1: '广西壮族自治区' },
  { value1: '西藏自治区', label1: '西藏自治区' },
  { value1: '宁夏回族自治区', label1: '宁夏回族自治区' },
  { value1: '新疆维吾尔自治区', label1: '新疆维吾尔自治区' },
  { value1: '香港特别行政区', label1: '香港特别行政区' },
  { value1: '澳门特别行政区', label1: '澳门特别行政区' }
];

const tableData = ref<any[]>([]);

const validateAddForm = () => {
  orgFormErrors.value.name = !newOrganizationName.value?.trim();
  return !Object.values(orgFormErrors.value).some(Boolean); // 所有字段非空才返回 true
};

const validateEditForm = () => {
  orgFormErrors.value.name = !newOrganizationName.value?.trim();
  orgFormErrors.value.location = (changeOrangLevel.value == '2');
  orgFormErrors.value.message = (changeOrangLevel.value == '2');

  return !Object.values(orgFormErrors.value).some(Boolean);
};

const getAllSecondaryOrganization = () => {
  request.get('/user/getAllSecondaryOrganization').then((res1) => {
    const secondList = res1.data;
    request.get('/user/getAllThirdOrganization').then((res2) => {
      console.log(111112222,res2)
      
      const thirdList = res2.data;

      // 一级组织固定为安徽省分公司
      const root = {
        id: 0,
        organizationName: '中国铁塔股份有限公司安徽省分公司',
        level: 0,
        levelLabel: '一级组织',
        children: []
      };

      const secondLevel = secondList.map((item: any) => ({
        id: item.id,
        organizationName: item.organizationName,
        level: 1,
        levelLabel: '二级组织',
        children: []
      }));

      const grouped = thirdList.reduce((acc: any, cur: any) => {
        acc[cur.secondaryID] = acc[cur.secondaryID] || [];
        acc[cur.secondaryID].push({
          id: cur.id,
          organizationName: cur.organizationName,
          level: 2,
          levelLabel: '三级组织',
          province: cur.province,
          description: cur.description,
          secondaryID: cur.secondaryID,
          secondaryName: cur.secondaryName
        });
        return acc;
      }, {});

      secondLevel.forEach((node: any) => {
        node.children = grouped[node.id] || [];
      });

      root.children = secondLevel;
      tableData.value = [root];
    });
  });
};

const append = (data: any) => {
  orgFormErrors.value = {
  name: false,
  location: false,
  message: false
};
  newOrganizationName.value = ''
  OrganizationLocation.value = ''
  message.value = ''
  visible.value = true;
  upOrganization.value = data.organizationName;
  upOrganizationId.value = data.id;
};
const changeOrangLevel = ref('')
const primaryOrganizationName = ref('')//获取原先的名字
const change = (data: any) => { 
  orgFormErrors.value = {
  name: false,
  location: false,
  message: false
};
  primaryOrganizationName.value = data.organizationName
  changeOrangLevel.value = data.level
  changeItem.value = data;
  visible1.value = true;
  changeId.value = data.id;
  newOrganizationName.value = data.organizationName;
  OrganizationLocation.value = data.province;
  message.value = data.description;
  NewsecondId.value = data.secondaryID;
  secondaryName.value = data.secondaryName;
};
const deleteOrganLevel = ref('')
const remove = (data: any) => {
  deleteOrganLevel.value = data.level
  deleteItem.value = data;
  centerDialogVisible.value = true;
};

const sumbitMessage = () => {
  if (!newOrganizationName.value) return;

  if(upOrganization.value == '中国铁塔股份有限公司安徽省分公司'){
    request.post('/user/insertSecondaryOrganization', {
    id: null,
    organizationName: newOrganizationName.value,
  }).then((res) => {
    showMessage(res);
    getAllSecondaryOrganization();
    visible.value = false;
  });
}else {
  request.post('/user/insertThirdOrganization', {
    id: null,
    secondaryID: upOrganizationId.value,
    organizationName: newOrganizationName.value,
    province: OrganizationLocation.value,
    description: message.value
  }).then((res) => {
    showMessage(res);
    getAllSecondaryOrganization();
    visible.value = false;
  });
} 
  }
const changeMessage = () => {
  if (changeOrangLevel.value == '1') {
    request.post('/user/updateSecondaryOrganization', {
    id: changeId.value,
    organizationName: newOrganizationName.value,
    primaryOrganizationName:primaryOrganizationName.value,
  }).then((res) => {
    showMessage(res);
    getAllSecondaryOrganization();
    visible1.value = false;
  });
  }else {
    request.post('/user/updateThirdOrganization', {
    id: changeId.value,
    secondaryID: NewsecondId.value,
    organizationName: newOrganizationName.value,
    primaryOrganizationName:primaryOrganizationName.value,
    province: OrganizationLocation.value,
    description: message.value
  }).then((res) => {
    showMessage(res);
    getAllSecondaryOrganization();
    visible1.value = false;
  });
  }
};

const deleteOri = () => {
  const formData = new FormData();

  if(deleteOrganLevel.value == '1'){
    //删除的是二级组织
    formData.append('secondaryID', deleteItem.value.id);
  request.post('/user/deleteSecondaryOrganizationByID', formData).then((res) => {
    showMessage(res);
    getAllSecondaryOrganization();
    centerDialogVisible.value = false;
  });
  }else {
    formData.append('thirdID', deleteItem.value.id);
  request.post('/user/deleteThirdOrganizationByID', formData).then((res) => {
    showMessage(res);
    getAllSecondaryOrganization();
    centerDialogVisible.value = false;
  });
  }
};

onMounted(() => {
  getAllSecondaryOrganization();
});
</script>

<style scoped>

.my-header {
  display: flex;
  justify-content: space-between;
}
.input-text {
  margin-top: 0.9rem;
  margin-bottom: 0.5rem;
}

.required {
  color: red;
  margin-right: 2px;
}
.error-text {
  color: red;
  font-size: 12px;
  margin: 4px 0 0 0;
}

</style>